/**
 * 
 */
package com.pxingg.voice;

import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pxingg.exception.XException;

/**
 * @author pxingg
 * 
 */
public class WavData
{
    /**
     * The log of this class
     */
    static Log log = LogFactory.getLog(WavData.class);

    /**
     * The format of the Voices data
     */
    private AudioFormat format = null;

    /**
     * The data of the Voices
     */
    private byte[] data = null;

    /**
     * The name of the Voices
     */
    private String name = null;
    /**
     * The file store the wave
     */
    private String file = null;

    /**
     * set the voice name and file
     * 
     * @param name
     *            the voice name
     * @param file
     *            the voice file
     */
    public WavData(final String name, final String file)
    {
        this.name = name;
        this.file = file;
    }

    /**
     * @return the data
     */
    public byte[] getData()
    {
        return data;
    }

    /**
     * @return the file
     */
    public String getFile()
    {
        return file;
    }

    /**
     * @return the format
     */
    public AudioFormat getFormat()
    {
        return format;
    }

    /**
     * @return the name
     */
    public String getName()
    {
        return name;
    }

    /**
     * load the voice to the memery
     * 
     * @throws XException
     */
    public void loadVoices() throws XException
    {
        if (name == null || file == null)
        {
            throw new XException("WavData name or file is null");
        }

        WavData.log.debug("begin to load voice " + name + "->" + file);

        try
        {
            // open the audio input stream
            final AudioInputStream audioStream = AudioSystem.getAudioInputStream(new File(file));

            format = audioStream.getFormat();

            // get the number of bytes to read
            final int length = (int) (audioStream.getFrameLength() * format.getFrameSize());

            // read the entire stream
            data = new byte[length];
            final DataInputStream is = new DataInputStream(audioStream);

            is.readFully(data);
        }
        catch (final UnsupportedAudioFileException e)
        {
            WavData.log.error(e);
            throw new XException(e.getMessage());
        }
        catch (final IOException e)
        {
            WavData.log.error(e);
            throw new XException(e.getMessage());
        }
    }
}
